home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 14320 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c,comp.unix.programmer
  4. Subject: Re: Q: '\n' character
  5. Date: Sat, 13 Apr 96 11:54:33 GMT
  6. Organization: none
  7. Message-ID: <829396473snz@genesis.demon.co.uk>
  8. References: <4kj66f$k0o@ren.cei.net> <1996Apr11.192937.25676@sq.com>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <1996Apr11.192937.25676@sq.com> msb@sq.com "Mark Brader" writes:
  15.  
  16. >> > Is there a function or some sort of way that I could remove '\n'
  17. >> > charecter form the end of the string. 
  18. >> 
  19. >> fgets(buffer, file); 
  20. >> buffer[strlen(buffer)-1]=0;  
  21. >> 
  22. >> It may not be the fastest, but it is darned near the easiest. 
  23. >
  24. >Or the buggiest.  Instead use:
  25. >
  26. >  len = strlen (buffer);
  27. >  if (len > 0 && buffer[len-1] == '\n') buffer[len-1] = '\0';
  28. >
  29. >Both tests in the "if" are necessary.
  30.  
  31. Not exactly true. fgets() can never place a zero length string in the
  32. buffer. However its return value can be a null pointer on end-of-file or
  33. failure and that condition must be tested for. fgets() will leave the buffer
  34. unchanged if it encounters end-of-file but that is the only case where
  35. you could legally test for and possibly find a zero length string. So the
  36. code should look something like:
  37.  
  38.     if (fgets(buffer, file) != NULL) {
  39.         size_t len = strlen(buffer);
  40.  
  41.         if (buffer[len-1] == '\n') buffer[len-1] = '\0';
  42.     }
  43.  
  44. >In the specific case of a string obtained from fgets(), we can be
  45. >sure that if there is a newline then it is the last character.
  46. >This leads to the alternative approach:
  47. >
  48. >  ptr = strchr (buffer, '\n');   /* or strrchr() */
  49. >  if (ptr) *ptr = '\0';
  50.  
  51. Or the very alternative approach:
  52.  
  53.       strtok(buffer, "\n");
  54.  
  55. But in both cases you still need to test the return code of fgets().
  56.  
  57. -- 
  58. -----------------------------------------
  59. Lawrence Kirby | fred@genesis.demon.co.uk
  60. Wilts, England | 70734.126@compuserve.com
  61. -----------------------------------------
  62.